package model

import "time"

const tableName = "system_resources"

type Resource struct {
	Id         int32     `json:"id" form:"id"`
	Title      string    `json:"title" form:"title"`     //资源名称
	Expand     bool      `json:"expand" form:"expand"`   // 是否展开
	Disabled   bool      `json:"disabled" form:"expand"` //是否激活
	ParentId   int32     `json:"parentId" form:"expand"` //父组件
	Path       string    `json:"path" form:"expand"`     // 资源路径
	CreateTime time.Time `json:"createTime" orm:"auto_now_add;type(date)" form:"expand"`
	UpdateTime time.Time `json:"updateTime" orm:"auto_now_add;type(date)" form:"expand"`
}

func (this *Resource) SaveResources(resource Resource) error {
	var err error
	if resource.Id == 0 {
		// do insert
		_, err = engine.Insert(&resource)
	} else {
		// do update
		_, err = engine.Update(resource)
	}

	return err
}

func (*Resource) QueryByPrimarykey(id int32) (resource Resource, err error) {
	r := &Resource{}
	_, err = engine.ID(id).Get(&r)
	return *r, err
}

func (*Resource) QueryAllResource() (resources []Resource, err error) {
	rList := make([]Resource, 0)
	err = engine.Table(tableName).Find(&rList)
	return rList, err
}

func (*Resource) Query(resource Resource, pageSize, currentPage int) (resources []Resource, err error) {
	rList := make([]Resource, 0)
	session := engine.Table(tableName)
	if resource.Id != 0 {
		session.Where("id=?", resource.Id)
	}
	if resource.ParentId != 0 {
		session.Where("parent_id=?", resource.ParentId)
	}
	if len(resource.Title) > 0 {
		session.Where("title=?", resource.Title)
	}
	err = session.Limit(pageSize, currentPage).Find(&rList)
	return rList, err
}
